{% extends 'dashboard/base.html' %}
{% load static %}

{% block title %}分类管理 - 后台管理{% endblock %}

{% block content %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">活动分类管理</h1>
    <div class="btn-toolbar mb-2 mb-md-0">
        <button class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#createCategoryModal">
            <i class="bi bi-plus-circle"></i> 添加分类
        </button>
        <a href="{% url 'dashboard:activity_management' %}" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> 返回活动管理
        </a>
    </div>
</div>

<!-- 搜索和统计 -->
<div class="row mb-4">
    <div class="col-md-6">
        <form method="get" class="d-flex">
            <input type="text" name="search" class="form-control me-2" placeholder="搜索分类名称..." 
                   value="{{ search_query }}">
            <button type="submit" class="btn btn-outline-primary">搜索</button>
        </form>
    </div>
    <div class="col-md-6 text-end">
        <span class="text-muted">共 {{ categories.count }} 个分类</span>
    </div>
</div>

<!-- 分类列表 -->
<div class="card shadow">
    <div class="card-body">
        {% if categories %}
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>分类名称</th>
                        <th>图标</th>
                        <th>描述</th>
                        <th>默认分类</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for category in categories %}
                    <tr id="category-{{ category.id }}">
                        <td>{{ category.id }}</td>
                        <td>
                            <strong>{{ category.name }}</strong>
                        </td>
                        <td>
                            {% if category.icon %}
                            <i class="{{ category.icon }}"></i>
                            <code class="ms-1">{{ category.icon }}</code>
                            {% else %}
                            <span class="text-muted">无</span>
                            {% endif %}
                        </td>
                        <td>
                            {% if category.description %}
                            <span title="{{ category.description }}">
                                {{ category.description|truncatechars:30 }}
                            </span>
                            {% else %}
                            <span class="text-muted">无描述</span>
                            {% endif %}
                        </td>
                        <td>
                            {% if category.is_default %}
                            <span class="badge bg-success">是</span>
                            {% else %}
                            <span class="badge bg-secondary">否</span>
                            {% endif %}
                        </td>
                        <td>{{ category.created_at|date:"Y-m-d H:i" }}</td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-warning btn-edit-category" 
                                        data-category-id="{{ category.id }}"
                                        title="编辑分类">
                                    <i class="bi bi-pencil"></i> 编辑
                                </button>
                                <button class="btn btn-danger btn-delete-category" 
                                        data-category-id="{{ category.id }}"
                                        data-category-name="{{ category.name }}"
                                        title="删除分类">
                                    <i class="bi bi-trash"></i> 删除
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="text-center py-5">
            <i class="bi bi-inbox display-1 text-muted"></i>
            <h4 class="text-muted mt-3">暂无分类数据</h4>
            <p class="text-muted">点击上方按钮添加第一个活动分类</p>
        </div>
        {% endif %}
    </div>
</div>

<!-- 创建分类模态框 -->
<div class="modal fade" id="createCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建活动分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createCategoryForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="categoryName" class="form-label">分类名称 *</label>
                        <input type="text" class="form-control" id="categoryName" name="name" required>
                        <div class="form-text">分类名称应该简洁明了</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="categoryDescription" class="form-label">分类描述</label>
                        <textarea class="form-control" id="categoryDescription" name="description" rows="3"></textarea>
                        <div class="form-text">简要描述这个分类的特点</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="categoryIcon" class="form-label">图标类名</label>
                        <input type="text" class="form-control" id="categoryIcon" name="icon" 
                               placeholder="bi bi-people 或 fas fa-users">
                        <div class="form-text">
                            使用 Bootstrap Icons (bi) 或 Font Awesome (fas) 图标类名
                            <a href="https://icons.getbootstrap.com/" target="_blank" class="ms-1">查看图标</a>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="isDefault" name="is_default">
                            <label class="form-check-label" for="isDefault">
                                设为默认分类
                            </label>
                        </div>
                        <div class="form-text">新用户创建活动时会默认选择此分类</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">创建分类</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑分类模态框 -->
<div class="modal fade" id="editCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑活动分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editCategoryForm">
                <input type="hidden" id="editCategoryId" name="category_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="editCategoryName" class="form-label">分类名称 *</label>
                        <input type="text" class="form-control" id="editCategoryName" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editCategoryDescription" class="form-label">分类描述</label>
                        <textarea class="form-control" id="editCategoryDescription" name="description" rows="3"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editCategoryIcon" class="form-label">图标类名</label>
                        <input type="text" class="form-control" id="editCategoryIcon" name="icon">
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="editIsDefault" name="is_default">
                            <label class="form-check-label" for="editIsDefault">
                                设为默认分类
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">更新分类</button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 创建分类表单提交
    document.getElementById('createCategoryForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        fetch('{% url "dashboard:category_create" %}', {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('createCategoryModal'));
                modal.hide();
                
                // 显示成功消息
                showAlert('success', data.message);
                
                // 重新加载页面
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                showAlert('danger', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', '创建失败，请重试');
        });
    });

    // 编辑分类按钮点击
    document.querySelectorAll('.btn-edit-category').forEach(btn => {
        btn.addEventListener('click', function() {
            const categoryId = this.dataset.categoryId;
            
            // 获取分类数据
            fetch(`{% url 'dashboard:category_edit' 0 %}`.replace('0', categoryId))
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const category = data.category;
                        
                        // 填充表单
                        document.getElementById('editCategoryId').value = category.id;
                        document.getElementById('editCategoryName').value = category.name;
                        document.getElementById('editCategoryDescription').value = category.description || '';
                        document.getElementById('editCategoryIcon').value = category.icon || '';
                        document.getElementById('editIsDefault').checked = category.is_default;
                        
                        // 显示模态框
                        const modal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
                        modal.show();
                    } else {
                        showAlert('danger', '获取分类数据失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('danger', '获取分类数据失败');
                });
        });
    });

    // 编辑分类表单提交
    document.getElementById('editCategoryForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const categoryId = document.getElementById('editCategoryId').value;
        
        fetch(`{% url 'dashboard:category_edit' 0 %}`.replace('0', categoryId), {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('editCategoryModal'));
                modal.hide();
                
                // 显示成功消息
                showAlert('success', data.message);
                
                // 重新加载页面
                setTimeout(() => {
                    location.reload();
                }, 1500);
            } else {
                showAlert('danger', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', '更新失败，请重试');
        });
    });

    // 删除分类
    document.querySelectorAll('.btn-delete-category').forEach(btn => {
        btn.addEventListener('click', function() {
            const categoryId = this.dataset.categoryId;
            const categoryName = this.dataset.categoryName;
            
            if (confirm(`确定要删除分类 "${categoryName}" 吗？\n\n此操作不可撤销！`)) {
                fetch(`{% url 'dashboard:category_delete' 0 %}`.replace('0', categoryId), {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 从表格中移除该行
                        document.getElementById(`category-${categoryId}`).remove();
                        showAlert('success', data.message);
                    } else {
                        showAlert('danger', data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('danger', '删除失败，请重试');
                });
            }
        });
    });

    // 显示提示消息
    function showAlert(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show mt-3`;
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        document.querySelector('main').insertBefore(alertDiv, document.querySelector('main').firstChild);
        
        // 自动移除提示
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 5000);
    }

    // 重置创建表单当模态框关闭时
    document.getElementById('createCategoryModal').addEventListener('hidden.bs.modal', function() {
        document.getElementById('createCategoryForm').reset();
    });
});
</script>
{% endblock %}